<template>
  <div style="width: 100%">
    <div class="common-layout">
      <div class="content-header">
        <h1>
          数据统计
          <small>订单统计</small>
          <el-button @click="refreshData" type="primary">刷新数据</el-button>
        </h1>
        <el-breadcrumb separator-class="el-icon-arrow-right" class="breadcrumb">
          <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
          <el-breadcrumb-item>数据统计</el-breadcrumb-item>
          <el-breadcrumb-item>订单统计</el-breadcrumb-item>
        </el-breadcrumb>
      </div>
    </div>

    <!-- 图表容器 -->
    <div class="chart-box">
      <div class="chart-title">订单统计</div>
      <div class="chart-wrapper">
        <div id="chart" class="chart"></div>
        <div id="dateChart" class="chart"></div>
      </div>
    </div>
  </div>
</template>


<style scoped>
@import '../css/style.css';

.chart-title {
  font-size: 18px;
  font-weight: bold;
  margin-bottom: 10px;
  text-align: center;
}

.chart-box {
  width: 100%;
  height: auto;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
  padding: 20px;
  border-radius: 8px;
  background: #fff;
}

.chart-wrapper {
  display: flex;
  justify-content: space-between;
  gap: 20px;
  flex-wrap: wrap; /* 允许在小屏幕下换行 */
}

.chart {
  flex: 1;
  min-width: 45%; /* 每个图表最小宽度 */
  height: 600px;
}
</style>


<script setup>
import { ref, onMounted, onBeforeUnmount } from 'vue';
import * as echarts from 'echarts';
import service from '@/util/http';

// 响应式变量
const chartData = ref([]);
const dateChartData = ref([]);
const chartInstance = ref(null);
const dateChartInstance = ref(null);

// 初始化图表
const initCharts = () => {
  if (!chartInstance.value) {
    chartInstance.value = echarts.init(document.getElementById('chart'));
  }
  if (!dateChartInstance.value) {
    dateChartInstance.value = echarts.init(document.getElementById('dateChart'));
  }
};

// 渲染车次订单饼图
const renderChart = () => {
  if (!chartInstance.value) initCharts();
  chartInstance.value.setOption({
    title: { text: '不同调度车次订单占比', left: 'center' },
    tooltip: { trigger: 'item', formatter: "{a} <br/>{b}: {c} ({d}%)" },
    legend: { bottom: '10%', left: 'center' },
    series: [{
      name: '车次订单',
      type: 'pie',
      radius: '50%',
      data: chartData.value.map(item => ({
        value: item.orderCount, name: item.dispatchId
      })),
      emphasis: {
        itemStyle: {
          shadowBlur: 10, shadowOffsetX: 0,
          shadowColor: 'rgba(0, 0, 0, 0.5)'
        }
      }
    }]
  });
};

// 渲染每日订单折线图
const renderDateChart = () => {
  if (!dateChartInstance.value) initCharts();
  dateChartInstance.value.setOption({
    title: { text: '每日订单数量统计', left: 'center' },
    tooltip: { trigger: 'axis', formatter: "{b}<br/>订单数: {c}" },
    xAxis: { type: 'category', data: dateChartData.value.map(item => item.date), axisLabel: { rotate: 45 } },
    yAxis: { type: 'value', name: '订单数' },
    series: [{
      name: '订单数量',
      type: 'line',
      data: dateChartData.value.map(item => item.orderCount),
      smooth: true,
      lineStyle: { width: 2 },
      itemStyle: { color: '#5470C6' }
    }]
  });
};

// 获取车次订单数据
const fetchChartData = async () => {
  const res = await service.get('/admin/orders/getOrderStatistics');
  if (res.data.flag) {
    chartData.value = res.data.data;
    renderChart();
  } else {
    console.error(res.data.message);
  }
};

// 获取每日订单数据
const fetchDateChartData = async () => {
  const res = await service.get('/admin/orders/getDateOrderStatistics');
  if (res.data.flag) {
    dateChartData.value = res.data.data;
    renderDateChart();
  } else {
    console.error(res.data.message);
  }
};

// 生命周期钩子
onMounted(() => {
  initCharts();
  fetchChartData();
  fetchDateChartData();
});
onBeforeUnmount(() => {
  chartInstance.value?.dispose();
  dateChartInstance.value?.dispose();
});

// 刷新数据方法
const refreshData = async () => {
  try {
    // 清空当前数据
    chartData.value = [];
    dateChartData.value = [];

    // 显示加载状态
    chartInstance.value?.showLoading();
    dateChartInstance.value?.showLoading();

    // 重新获取数据
    await Promise.all([fetchChartData(), fetchDateChartData()]);

    // 隐藏加载状态
    chartInstance.value?.hideLoading();
    dateChartInstance.value?.hideLoading();

    console.log("数据刷新成功！");
  } catch (error) {
    console.error("刷新数据时出错：", error);
    // 隐藏加载状态以避免残留
    chartInstance.value?.hideLoading();
    dateChartInstance.value?.hideLoading();
  }
};

</script>
